<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>
    <template>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        highlight-current-row
      >
        <el-table-column label="ID" align="center" width="80px">
          <template v-slot="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="环境" align="center" width="200px">
          <template v-slot="{row}">
            <span>{{ row.envName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="环境参数名" align="center">
          <template v-slot="{row}">
            {{ row.serverNameList }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template v-slot="{row, $index}">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini" @click="del(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-dialog :visible.sync="dialogFormVisible" width="1000px" title="环境参数" :close-on-click-modal="false">
      <div style="text-align: right; margin-top: -20px;">
        <el-button-group style="margin-top: -20px; margin-right: 0px; margin-bottom: 5px;">
          <el-tooltip content="添加环境参数" placement="top" :open-delay="500">
            <el-button icon="el-icon-plus" type="warning" icon-class="skill" size="mini" @click="newTableRow()" />
          </el-tooltip>
        </el-button-group>
      </div>
      <el-table
        ref="stepsTable"
        border
        size="mini"
        :data="TableData"
      >
        <el-table-column prop="serverName" label="ID" width="45" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="serverName" label="参数名" min-width="20%">
          <template v-slot="scope">
            <el-input v-model="scope.row.serverName" autosize class="item" @blur="removeSpecialSymbols(scope.row, $event)" />
          </template>
        </el-table-column>
        <el-table-column prop="value" label="参数值" min-width="50%">
          <template v-slot="scope">
            <el-input v-model="scope.row.value" autosize class="item" />
          </template>
        </el-table-column>
        <el-table-column prop="value" label="描述" min-width="25%">
          <template v-slot="scope">
            <el-input v-model="scope.row.desc" autosize class="item" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="50">
          <template v-slot="scope">
            <el-tooltip :tabindex="-1" content="删除" placement="top" :open-delay="500">
              <span class="icon-wrapper"><i class="el-icon-close icon-style" @click="delTableRow(scope.$index)" /></span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createServer()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="newDialogFormVisible" width="480px" title="环境" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="newEnvName" label-position="left" label-width="80px">
        <el-form-item label="环境名" prop="envName">
          <el-input v-model="newEnvName.envName" placeholder="请输入环境名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createEnv()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style>

</style>

<script>
import { addEnv, addServer, findList, selectIdByEnvName, deleteEnvByName, deleteServerById } from '@/api/functional_test/env_param'
export default {
  data() {
    return {
      newEnvName: {
        projectId: this.$store.getters.projectId,
        envName: ''
      },
      TableData: [
      ],
      list: null,
      flag: '',
      listLoading: true,
      dialogFormVisible: false,
      newDialogFormVisible: false,
      rules: {
        envName: [
          { required: true, message: '请输入环境名', trigger: 'blur' },
          { max: 50, message: '环境 长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    filter() {
      this.fetchData()
    },
    handleCreate() {
      this.newDialogFormVisible = true
    },
    handleUpdate(row) {
      this.TableData = []
      this.flag = row.envName
      this.TableData.push(...row.envParams.map((item) => {
        return {
          id: item.id,
          envName: item.envName,
          serverName: item.serverName,
          value: item.value,
          desc: item.desc,
          projectId: item.projectId
        }
      }))
      this.dialogFormVisible = true
    },
    newTableRow() {
      this.TableData.push({
        envName: this.flag,
        serverName: '',
        value: '',
        projectId: this.$store.getters.projectId
      })
    },
    fetchData() {
      this.newEnvName = { projectId: this.$store.getters.projectId, envName: '' }
      this.listLoading = true
      findList({ projectId: this.$store.getters.projectId }).then(response => {
        this.list = []
        this.list.push(...response.data.map((item) => {
          return {
            id: item.id,
            envName: item.envName,
            envParams: item.envParams,
            serverNameList: []
          }
        }))
        this.listLoading = false
        for (let j = 0; j < this.list.length; j++) {
          selectIdByEnvName(this.$store.getters.projectId, this.list[j].envName).then(response => {
            this.list[j].id = response.data.id
          })
          for (let i = 0; i < this.list[j].envParams.length; i++) {
            this.list[j].serverNameList.push(this.list[j].envParams[i].serverName)
          }
        }
        this.listLoading = false
      })
    },
    createEnv() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addEnv(this.newEnvName).then(res => {
            this.newDialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    createServer() {
      addServer(this.TableData).then(res => {
        this.dialogFormVisible = false
        this.$message({ message: '添加成功!', type: 'success' })
        this.fetchData()
      })
    },
    delTableRow(index) {
      this.$confirm('是否确认删除当前服务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.TableData[index].id !== undefined || this.TableData[index].id === '') {
          deleteServerById(this.TableData[index].id).then(res => {
            this.TableData.splice(index, 1)
          })
        } else {
          this.TableData.splice(index, 1)
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    del(row, index) {
      this.$confirm('此删除操作，会一并删除当前环境下所有服务，是否确定？', '删除当前环境和服务', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteEnvByName(this.$store.getters.projectId, row.envName).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      })
    },
    // 限制输入特殊字符
    removeSpecialSymbols(rowData, e) {
      e.target.value = e.target.value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, '')
      rowData.serverName = e.target.value
    }
  }
}
</script>
